package com.szt.sy.controller.system.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.szt.sy.anontation.Authority;
import com.szt.sy.anontation.AuthorityConfig;
import com.szt.sy.anontation.SysLog;
import com.szt.sy.common.AuthorityCommon;
import com.szt.sy.common.RegexConst;
import com.szt.sy.controller.base.AdminBaseController;
import com.szt.sy.entity.common.Editable;
import com.szt.sy.entity.system.Role;
import com.szt.sy.entity.system.User;
import com.szt.sy.service.system.role.RoleService;
import com.szt.sy.service.system.user.UserService;
import com.szt.sy.util.date.DateUtil;
import com.szt.sy.util.encrypt.shiro.PasswordInfo;
import com.szt.sy.util.encrypt.shiro.Sha1ShiroEncrypt;
import com.szt.sy.util.excel.ObjectExcelView;
import com.szt.sy.vo.rep.base.RepBaseVO;
import com.szt.sy.vo.req.page.ReqPageVO;

/**
 * 会员管理
 * 
 * @author wwy
 *
 * @version
 */
@Controller
@AuthorityConfig(prefix = "/admin/user/list")
@RequestMapping(value = "admin/user")
public class UserController extends AdminBaseController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	
	/**
	 * 去列表页面
	 * 
	 */
	@Authority(name = AuthorityCommon.LIST)
	@GetMapping(value = "/list")
	public ModelAndView goPage(@RequestParam Map<String, Object> map) {
		ModelAndView mv = this.getModelAndView();
		// 列出所有系统用户角色
		List<Role> roleList = roleService.listAllNotTopRole();
		mv.addObject("roleList", roleList);
		mv.setViewName("system/user/user_list");
		mv.addObject("queryParam", map);
		// 按钮权限
		
		return mv;
	}
	
	/**
	 * 列表数据
	 */
	@SysLog("查询用户列表数据")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Authority(name = AuthorityCommon.LIST)
	@PostMapping(value = "/list")
	@ResponseBody
	public RepBaseVO list(ReqPageVO pageVO, @RequestParam Map<String, Object> map) {
		RepBaseVO repVO = new RepBaseVO<>();
		processParams(map);
		Page<User> page = processPage(pageVO);
		page = userService.list(page, map);
		List<User> varList = page.getRecords();
		Map<String, Object> resultInfo = new HashMap<>(2);
		resultInfo.put("data", varList);
		resultInfo.put("total", page.getTotal());
		return repVO.setCommonSuccess().setData(resultInfo);
	}
	
	/**
	 * 去新增页面
	 */
	@Authority(name = AuthorityCommon.ADD)
	@GetMapping(value = "/add")
	public ModelAndView goAdd(@RequestParam Map<String, Object> map) {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/user/user_edit");
		User entity = new User();
		List<Role> roleList = roleService.listAllNotTopRole();
		mv.addObject("roleList", roleList);
		mv.addObject("msg", "add");
		mv.addObject("entity", entity);
		mv.addObject("pd", map);
		return mv;
	}
	
	/**
	 * 保存
	 */
	@SysLog("添加用户数据")
	@Authority(name = AuthorityCommon.ADD)
	@PostMapping(value = "/add")
	@ResponseBody
	public RepBaseVO save(User entity) {
		RepBaseVO repVO = new RepBaseVO();
		entity.setVersion(1L);
		entity.setAddDate(new Date());
		PasswordInfo passwordInfo = Sha1ShiroEncrypt.encryptPassword(entity.getPassword());
		entity.setPassword(passwordInfo.getPassword());
		entity.setPasswordSalt(passwordInfo.getSalt());
		entity.setDel(false);
		entity.setEnable(true);
		userService.insert(entity);
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 去修改页面
	 */
	@Authority(name = AuthorityCommon.EDIT)
	@GetMapping(value = "/edit")
	public ModelAndView goEdit(String id) {
		ModelAndView mv = this.getModelAndView();
		User entity = userService.selectById(id);
		List<Role> roleList = roleService.listAllNotTopRole();
		mv.addObject("roleList", roleList);
		mv.setViewName("system/user/user_edit");
		mv.addObject("msg", "edit");
		mv.addObject("entity", entity);
		return mv;
	}
	
	/**
	 * 修改
	 */
	@SysLog("修改用户数据")
	@Authority(name = AuthorityCommon.EDIT)
	@PostMapping(value = "/edit")
	@ResponseBody
	public RepBaseVO edit(User entity) {
		RepBaseVO repVO = new RepBaseVO<>();
		User user = userService.selectById(entity.getId());
		if (user.getEditable().equals(Editable.NO)) {
			return repVO.setCommonFail().setMes("改用户不可编辑");
		}
		if (StringUtils.isNotBlank(entity.getRoleId())) {
			user.setRoleId(entity.getRoleId());
		}
		if (StringUtils.isNotBlank(entity.getName())) {
			user.setName(entity.getName());
		}
		if (StringUtils.isNotBlank(entity.getNickname())) {
			user.setNickname(entity.getNickname());
		}
		if (StringUtils.isNotBlank(entity.getPhone())) {
			user.setPhone(entity.getPhone());
		}
		if (StringUtils.isNotBlank(entity.getRemarks())) {
			user.setRemarks(entity.getRemarks());
		}
		if (StringUtils.isNotBlank(entity.getPassword())) {
			PasswordInfo passwordInfo = Sha1ShiroEncrypt.encryptPassword(entity.getPassword());
			user.setPassword(passwordInfo.getPassword());
			user.setPasswordSalt(passwordInfo.getSalt());
			
		}
		userService.updateById(user);
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 删除
	 */
	@SysLog("删除用户数据")
	@Authority(name = AuthorityCommon.DELETE)
	@PostMapping(value = "/delete")
	@ResponseBody
	public RepBaseVO delete(String id) {
		userService.delete(new EntityWrapper<User>().eq("id", id).eq("editable", Editable.YES));
		return RepBaseVO.newIntance().setCommonSuccess();
	}
	
	/**
	 * 批量删除
	 */
	@SysLog("批量删除用户数据")
	@SuppressWarnings({ "rawtypes" })
	@Authority(name = AuthorityCommon.DELETE)
	@PostMapping(value = "/deleteAll")
	@ResponseBody
	public RepBaseVO deleteAll(@RequestParam("ids[]") List<String> ids) {
		RepBaseVO repVO = new RepBaseVO<>();
		if (null != ids && !ids.isEmpty()) {
			userService.delete(new EntityWrapper<User>().in("id", ids).eq("editable", Editable.YES));
		}
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 导出用户信息到EXCEL
	 *
	 * @return
	 */
	@Authority(name = AuthorityCommon.LIST)
	@RequestMapping(value = "/excel")
	public ModelAndView exportExcel(@RequestParam Map<String, Object> map) {
		ModelAndView mv = this.getModelAndView();
		processParams(map);
		Map<String, Object> dataMap = new HashMap<>(2);
		List<String> titles = new ArrayList<>();
		titles.add("用户名");
		titles.add("姓名");
		titles.add("职位");
		titles.add("手机");
		titles.add("最近登录");
		titles.add("上次登录IP");
		dataMap.put("titles", titles);
		List<User> userList = userService.listAllUser(map);
		List<Map<String, Object>> varList = new ArrayList<>();
		for (int i = 0; i < userList.size(); i++) {
			Map<String, Object> vpd = new HashMap<>(7);
			vpd.put("var1", userList.get(i).getName());
			vpd.put("var2", userList.get(i).getNickname());
			String roleName = "";
			if (userList.get(i).getRole() != null) {
				roleName = userList.get(i).getRole().getRoleName();
			}
			vpd.put("var3", roleName);
			vpd.put("var4", userList.get(i).getPhone());
			vpd.put("var5", DateUtil.getTime(userList.get(i).getLastLogin()));
			vpd.put("var6", userList.get(i).getIp());
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		// 执行excel操作
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv, dataMap);
		
		return mv;
	}
	
	/***
	 * 处理输入参数
	 * 
	 * @param map
	 */
	private void processParams(Map<String, Object> map) {
		String sStartDate = (String) map.get("startDate");
		String sEndDate = (String) map.get("endDate");
		if (StringUtils.isBlank(sStartDate)) {
			map.put("startDate", null);
		} else {
			map.put("startDate", DateUtil.getStartTimeOfDate(sStartDate));
		}
		if (StringUtils.isBlank(sEndDate)) {
			map.put("endDate", null);
		} else {
			map.put("endDate", DateUtil.getEndTimeOfDate(sEndDate));
		}
		String sortDirection = (String) map.get("sortDirection");
		String sortColumn = (String) map.get("sortColumn");
		if (StringUtils.isNotBlank(sortColumn) && !sortColumn.matches(RegexConst.WORD)) {
			map.remove("sortColumn");
		}
		if (StringUtils.isNotBlank(sortDirection) && !sortDirection.matches(RegexConst.WORD)) {
			map.remove("sortDirection");
		}
	}
	
	/***
	 * 处理分页参数
	 * 
	 * @param pageVO
	 * @return
	 */
	private Page<User> processPage(ReqPageVO pageVO) {
		Page<User> page = new Page<>(pageVO.getCurrent(), pageVO.getSize());
		return page;
	}
	
}
